package com.yuneec.fly.views;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.RadioButton;

import com.yuneec.fly.R;

/**
 * Created by zd.zhang on 2016/7/15.
 */
public class CenterImgRadioButton extends RadioButton {
    private Drawable drawable;
    private int dWidth, dHeight, mX, mY;

    public CenterImgRadioButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public CenterImgRadioButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int mWidth = getMeasuredWidth();
        int mHeight = getMeasuredHeight();
        mX = (mWidth - dWidth) / 2;
        mY = (mHeight - dHeight) / 2;
    }

    @Override
    protected void drawableStateChanged() {
        if (drawable != null && drawable.isStateful()) {
            drawable.setState(getDrawableState());
        }
        super.drawableStateChanged();
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (drawable != null) {
            canvas.translate(mX, mY);
            drawable.draw(canvas);
            canvas.translate(-mX, -mY);
        }
    }

    private void init(Context context, AttributeSet attrs) {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ImageOption);
        drawable = a.getDrawable(R.styleable.ImageOption_imgSrc);
        if (drawable != null) {
            dWidth = a.getDimensionPixelOffset(R.styleable.ImageOption_imgWidth, drawable.getIntrinsicWidth());
            dHeight = a.getDimensionPixelOffset(R.styleable.ImageOption_imgHeight, drawable.getIntrinsicHeight());
            a.recycle();
            drawable.setBounds(0, 0, dWidth, dHeight);
        }
        setButtonDrawable(0);
        setGravity(Gravity.CENTER);
        setClickable(true);
    }
}
